<?php
namespace app\admin\controller;

use app\admin\controller\AdminBase;
use think\Db;
use think\Request;

class Rbac extends AdminBase
{
    public $user_id;

    public function _initialize()
    {
        parent::_initialize();
    }
    /**
     * 添加角色
     * @author cuibo weiai525@outlook.com at 2016-10-23
     */
    public function addRole()
    {
        if (request()->isGet()) {
            return view('');
        }
        // 添加角色时只添加name remark参数
        $data = Request::instance()->only(['name', 'remark']);
        $Validate = validate('Rbac');
        if (!$Validate->scene('addRole')->check($data)) {
            return $this->error($Validate->getError());
        }
        $roleModel = model('admin/Role');
        $roleModel->data($data, true);
        if (!$roleModel->save()) {
            return $this->error('系统错误');
        }
        return $this->success('角色添加成功');
    }
    /**
     * 编辑角色
     * @author cuibo weiai525@outlook.com at 2016-10-23
     * @return [type] [description]
     */
    public function editRole()
    {
        if (request()->isGet()) {
            return view('');
        }
        $data = Request::instance()->only(['name', 'remark', 'status', 'role_id']);
        $Validate = validate('Rbac');
        if (!$Validate->scene('addRole')->check($data)) {
            return $this->error($Validate->getError());
        }
        $roleModel = model('admin/Role');
        if (!$roleModel->save($data, ['role_id', $data['role_id']])) {
            return $this->error('系统错误');
        }
        return $this->success('角色修改成功');
    }
    /**
     * 编辑角色权限
     * @author cuibo weiai525@outlook.com at 2016-10-23
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function editRoleRule()
    {
        if (request()->isGet()) {
            return view('');
        }
        $data = Request::instance()->only(['rule_id', 'role_id']);
        $Validate = validate('Rbac');
        if (!$Validate->scene('editRoleRule')->check($data)) {
            return $this->error($Validate->getError());
        }
        $rule_id = $data['rule_id'];
        $rules = [];
        //传入空数组表示删除有权限，前端用数组索引0的值为空字符串表示空数组
        if ($rule_id[0] == '') {
            $roleRuleModel = model('admin/RoleRule');
            //删除原有数据，后面一次性插入
            $roleRuleModel->where('role_id', $data['role_id'])->delete();
            return $this->success('编辑权限成功');
        }
        $rules = db('rule')->where('rule_id', 'IN', $rule_id)->select();
        if (count($rules) != count($rule_id)) {
            return $this->error('rule_id有误');
        }
        $routeData = [];
        // 构造插入数据格式
        foreach ($rules as $key => $value) {
            $routeData[] = ['role_id' => $data['role_id'], 'rule_route' => $value['route'], 'rule_id' => $value['rule_id']];
        }
        $roleRuleModel = model('admin/RoleRule');
        //删除原有数据，后面一次性插入
        $roleRuleModel->where('role_id', $data['role_id'])->delete();
        if (!$roleRuleModel->saveAll($routeData, true)) {
            return $this->error('系统错误');
        }
        return $this->success('编辑权限成功');
    }
    /**
     * 删除角色
     * @author cuibo weiai525@outlook.com at 2016-10-23
     * @return [type] [description]
     */
    public function deleteRole()
    {
        $data = Request::instance()->only(['role_id']);
        $Validate = validate('Rbac');
        if (!$Validate->scene('deleteRole')->check($data)) {
            return $this->error($Validate->getError());
        }
        // 启动事务
        Db::startTrans();
        try {
            db('role')->where('role_id', $data['role_id'])->delete();
            db('role_rule')->where('role_id', $data['role_id'])->delete();
            db('user_role')->where('role_id', $data['role_id'])->delete();
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error('删除角色失败');
        }
        return $this->success('删除角色成功');
    }
    /**
     * 获取角色列表
     * @author cuibo weiai525@outlook.com at 2016-10-23
     * @return json [description]
     */
    public function getRoleList()
    {
        $roleModel = model('admin/Role');
        $data = $roleModel->select();
        if (request()->isAjax()) {
            return json($data);
        }
        return view('', ['list' => $data]);
    }
    /**
     * 获取指定角色的权限列表
     * @author cuibo weiai525@outlook.com at 2016-10-23
     * @return [type] [description]
     */
    public function getRoleRule()
    {
        $data = Request::instance()->only(['role_id']);
        $Validate = validate('Rbac');
        if (!$Validate->scene('getRoleRule')->check($data)) {
            return $this->error($Validate->getError());
        }
        $roleModel = model('admin/RoleRule');
        $data = $roleModel->where('role_id', $data['role_id'])->select();
        if (request()->isAjax()) {
            return json($data);
        }
        ///return json($data);
    }
    /**
     * 将用户添加到指定角色
     * @author cuibo weiai525@outlook.com at 2016-10-23
     */
    public function addRoleUser()
    {
        $data = Request::instance()->only(['role_id', 'user_id']);
        $Validate = validate('Rbac');
        if (!$Validate->scene('addUserRole')->check($data)) {
            return $this->error($Validate->getError());
        }
        $roleModel = model('admin/UserRole');
        $roleModel->data($data, true);
        if (!$roleModel->save()) {
            return $this->error('添加失败');
        }
        return $this->success('添加成功');
    }
    /**
     * 删除指定用户的指定角色
     * @author cuibo weiai525@outlook.com at 2016-10-23
     */
    public function deleteRoleUser()
    {
        if (request()->isGet()) {
            return view('');
        }
        $data = Request::instance()->only(['role_id', 'user_id']);
        $Validate = validate('Rbac');
        if (!$Validate->scene('deleteUserRole')->check($data)) {
            return $this->error($Validate->getError());
        }
        $roleModel = model('admin/UserRole');
        if (!$roleModel->where('user_id', $data['user_id'])->where('role_id', $data['role_id'])->delete()) {
            return $this->error('删除失败');
        }
        return $this->success('删除成功');
    }
    /**
     * 编辑用户角色
     * @author cuibo weiai525@outlook.com at 2016-10-23
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function editUserRole()
    {
        if (request()->isGet()) {
            return view('');
        }
        $data = Request::instance()->only(['user_id', 'role_id']);
        $Validate = validate('Rbac');
        if (!$Validate->scene('editUserRole')->check($data)) {
            return $this->error($Validate->getError());
        }
        $role_id = $data['role_id'];
        $roles = [];
        //传入空数组表示删除有权限，前端用数组索引0的值为空字符串表示空数组
        if ($role_id[0] == '') {
            $roleRuleModel = model('admin/UserRole');
            //删除原有数据，后面一次性插入
            $roleRuleModel->where('user_id', $data['user_id'])->delete();
            return $this->success('编辑权限成功');
        }
        $roles = db('role')->where('role_id', 'IN', $role_id)->select();
        if (count($roles) != count($role_id)) {
            return $this->error('rule_id有误');
        }
        $routeData = [];
        // 构造插入数据格式
        foreach ($roles as $key => $value) {
            $routeData[] = ['user_id' => $data['user_id'], 'role_id' => $value['role_id']];
        }
        $roleRuleModel = model('admin/UserRole');
        //删除原有数据，后面一次性插入
        $roleRuleModel->where('user_id', $data['user_id'])->delete();
        if (!$roleRuleModel->saveAll($routeData, true)) {
            return $this->error('系统错误');
        }
        return $this->success('编辑权限成功');
    }
    /**
     * 获取指定角色的用户列表
     * @author cuibo weiai525@outlook.com at 2016-10-23
     */
    public function getRoleUser()
    {
        $data = Request::instance()->only(['role_id']);
        $Validate = validate('Rbac');
        if (!$Validate->scene('getUserRule')->check($data)) {
            return $this->error($Validate->getError());
        }
        $userRoleModel = model('admin/UserRole');
        $data = $userRoleModel->where('role_id', $data['role_id'])->select();
        if (request()->isAjax()) {
            return json($data);
        }
        return view('',['list'=>$data]);
    }
    /**
     * 获取指定用户的角色列表
     * @author cuibo weiai525@outlook.com at 2016-10-23
     */
    public function getUserRole()
    {
        $data = Request::instance()->only(['user_id']);
        $Validate = validate('Rbac');
        if (!$Validate->scene('getUserRole')->check($data)) {
            return $this->error($Validate->getError());
        }
        $userRoleModel = model('admin/UserRole');
        $data = $userRoleModel->where('user_id', $data['user_id'])->select();
        if (request()->isAjax()) {
            return json($data);
        }
        return json($data);
    }
    /**
     * 添加权限规则
     * @author cuibo weiai525@outlook.com at 2016-10-23
     */
    public function addRule()
    {
        $data = Request::instance()->only(['route', 'name']);
        $Validate = validate('Rbac');
        if (!$Validate->scene('addRule')->check($data)) {
            return $this->error($Validate->getError());
        }
        $ruleModel = model('admin/Rule');
        $ruleModel->data($data, true);
        if (!$ruleModel->save()) {
            return $this->error('添加失败');
        }
        return $this->success('添加成功');
    }
    /**
     * 删除权限规则
     * @author cuibo weiai525@outlook.com at 2016-10-23
     */
    public function deleteRule()
    {
        $data = Request::instance()->only(['rule_id']);
        $Validate = validate('Rbac');
        if (!$Validate->scene('deleteRule')->check($data)) {
            return $this->error($Validate->getError());
        }
        // 启动事务
        Db::startTrans();
        try {
            db('rule')->where('rule_id', $data['rule_id'])->delete();
            db('role_rule')->where('rule_id', $data['rule_id'])->delete();
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error('删除角色失败');
        }
        return $this->success('删除角色成功');
    }
    /**
     * 查看权限规则列表
     * @author cuibo weiai525@outlook.com at 2016-10-23
     */
    public function getRule()
    {
        $roleModel = model('admin/Rule');
        $data = $roleModel->select();
        if (request()->isAjax()) {
            return json($data);
        }
        return view('', ['list' => $data]);
    }
    /**
     * 编辑规则
     * @author cuibo weiai525@outlook.com at 2016-10-23
     * @return [type] [description]
     */
    public function editRule()
    {
        if (request()->isGet()) {
            return view('');
        }
        $data = Request::instance()->only(['name', 'route', 'status', 'rule_id']);
        $Validate = validate('Rbac');
        if (!$Validate->scene('editRule')->check($data)) {
            return $this->error($Validate->getError());
        }
        $roleModel = model('admin/Rule');
        if (!$roleModel->save($data, ['rule_id', $data['rule_id']])) {
            return $this->error('系统错误');
        }
        return $this->success('规则修改成功');
    }

}
